﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dathuc
{
    public class DonThuc
    {
        private int heso;
        private int somu;

        public int Heso
        {
            get { return heso; }
            set { heso = value; }
        }

        public int Somu
        {
            get { return somu; }
            set { somu = value; }
        }

        public DonThuc()
        {
            somu = 0;
            heso = 0;
        }

        public DonThuc(string dt)
        {
            if (dt == "")
                return;
            //dt co dang ax^t
            int vitri = -1;
            dt = dt.Trim();
            dt = dt.ToLower();
            //tim vi tri chu x
            vitri = dt.IndexOf('x');
            if (vitri != -1) //tim thay chu x
            {
                //lay he so a
                char[] dis = new char[vitri];
                dt.CopyTo(0, dis, 0, vitri);
                Heso = int.Parse(new string(dis));

                //lay so mu t
                vitri = -1;
                vitri = dt.IndexOf('^'); //vi tri cua dau ^
                if (vitri != -1)
                {
                    dis = new char[dt.Length - vitri];
                    dt.CopyTo(vitri + 1, dis, 0, dt.Length - vitri - 1);
                    Somu = int.Parse(new string(dis));
                }
                else
                    Somu = 1;
            }
            else
            {
                Heso = int.Parse(dt);
                Somu = 0;
            }
        }

        public static DonThuc operator +(DonThuc dt1, DonThuc dt2)
        {
            DonThuc temp = new DonThuc();
            if (dt1.Somu != dt2.Somu)
                return null;
            temp.Heso = dt1.Heso + dt2.Heso;
            temp.Somu = dt1.Somu;
            return temp;
        }

        public static DonThuc operator *(DonThuc dt1, DonThuc dt2)
        {
            DonThuc temp = new DonThuc();
            temp.Heso = dt1.Heso * dt2.Heso;
            temp.Somu = dt1.Somu + dt2.Somu;
            return temp;
        }

        public override string ToString()
        {
            string chuoi = "";
            if (this.Heso == 0)
                return "";
            if (this.Heso < 0)
                chuoi += " - " + Math.Abs(this.Heso).ToString();
            else
                chuoi += this.Heso.ToString();
            if (this.Somu > 0)
                chuoi += "x^" + this.Somu.ToString();

            return chuoi;
        }
    }
}
